package com.woniuxy.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.woniuxy.config.Alipay;
import com.woniuxy.config.AlipayConfig;
import com.woniuxy.entity.Appointment;
import com.woniuxy.entity.CarOrder;
import com.woniuxy.service.AppointmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@Slf4j
public class AlipayController {
    @Resource
    private AppointmentService appointmentService;
    //请求支付
    @RequestMapping("/pay")
    public String getAliPayOrderStr(CarOrder carOrder) {
        System.out.println("py请求进来了");
        return Alipay.getAliPayOrderStr(carOrder);
    }
    //同步回调地址
    @RequestMapping("/return")
    public String synchronous(HttpServletRequest request, Model model) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams  = request.getParameterMap();
        log.info("支付宝同步参数："+requestParams);
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            log.info("valueStr = "+valueStr);
            params.put(key, valueStr);
        }
        String out_trade_no = new String(request.getParameter("out_trade_no"));
        log.info("支付宝同步回调订单号："+out_trade_no);
        String trade_no = new String(request.getParameter("trade_no"));
        log.info("支付宝同步回调支付宝交易号："+out_trade_no);
        log.info(params.toString());
        model.addAttribute("totalAmount",new String(request.getParameter("total_amount")));
        log.info("同步回调交易金额："+new String(request.getParameter("total_amount")));
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        if(verify_result){
            //验证成功
            log.info("同步回调成功");
            return "paySuccess";
        }else{
            log.info("失败");
            return "{suecess:'失败'}";
        }
    }

    @RequestMapping("/notify")
    @Transactional
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //接收参数进行校验
        Map<String, String> parameters = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            parameters.put(key, valueStr);
        }
        log.info("parameters is [parameters={}]", parameters);
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no"));
        log.info("支付宝异步回调订单号："+out_trade_no);
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no"));
        log.info("支付宝异步回调交易号："+trade_no);
        //交易状态
        String trade_status = new String(request.getParameter("trade_status"));
        log.info("支付宝异步回调订单状态："+trade_status);
        log.info("支付宝异步回调用户id："+request.getParameter("passback_params"));
        boolean verify_result = AlipaySignature.rsaCheckV1(parameters, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        PrintWriter out = response.getWriter();

        log.info("999999999999"+verify_result);
        if(verify_result){//验证成功
            //请在这里加上商户的业务逻辑程序代码

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                log.info("++++++++++++++++++TRADE_FINISHED");
                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if (trade_status.equals("TRADE_SUCCESS")){
                log.info("++++++++++++++++++TRADE_SUCCESS");
//                orderService.changeStatus(out_trade_no,2);
                //判断该笔订单是否在商户网站中已经做过处理
                 /*List<String> of = ios.findByOutTradeNo(out_trade_no);
                 String str = "";
                 for(int i = 0 ; i < of.size();i++){
                     str = of.get(0);
                 }
                System.out.println("zhifubao huidiao:"+str);
                log.info("支付宝回调查询订单信息："+of);
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序

                if(of != null){
                    System.out.println("订单号不为空");
                    int result = ios.payMoney(str);
                    if(result == 1){
                        System.out.println("修改订单状态为支付");
                    }else{
                        System.out.println("修改订单状态失败");
                    }

                }else {

                }*/
            }
            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            //如果有做过处理，不执行商户的业务程序

            //注意：
            //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。

            //请不要修改或删除
            out.println("success");
            log.info("异步回调：成功");

        }else{//验证失败
            log.info("验证失败");
            out.println("fail");
        }
    }
}
